﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Barcode;
using System.Windows;
using System.Collections.ObjectModel;
using System.IO;
using Helpers;
using System.Windows.Media;
using System.Timers;
using System.Xml.Linq;

namespace ISBNScanner
{
    public class MainWindowViewModel : NotifyPropertyChangedBase
    {
        public ObservableCollection<TitleAndCopies> AllNumbers { get; set; }

        TitleAndCopies _selectedTitle;
        public TitleAndCopies SelectedTitle
        {
            get { return _selectedTitle; }
            set
            {
                _selectedTitle = value; 
                NotifyPropertyChanged("SelectedTitle");
            }
        }
        ObservableCollection<string> _barLog;
        public ObservableCollection<string> BarLog
        {
            get { return _barLog; }
            set
            {
                _barLog = value;
                NotifyPropertyChanged("BarLog");
            }
        }

        Color _backgroundColor;
        public Color BackgroundColor
        {
            get { return _backgroundColor; }
            set
            {
                _backgroundColor = value;
                NotifyPropertyChanged("BackgroundColor");
            }
        }

        bool _animate;
        public bool Animate
        {
            get { return _animate; }
            set
            {
                _animate = value;
                NotifyPropertyChanged("Animate");
            }
        }

        string _status;
        public string Status
        {
            get { return _status; }
            set
            {
                _status = value;
                NotifyPropertyChanged("Status");
            }
        }

        MainWindow mainWindow = null;

        public void LoadData()
        {
            try
            {
                AllNumbers = new ObservableCollection<TitleAndCopies>();
                if (File.Exists("isbn.txt"))
                {
                    XDocument doc = XDocument.Load("isbn.txt");
                    AllNumbers = new ObservableCollection<TitleAndCopies>(doc
                        .Element("scanned").Elements("isbn")
                        .Select(x => new TitleAndCopies
                        {
                            Isbn = x.Nodes().OfType<XText>().First().Value,
                            Copies = new ObservableCollection<string>(
                                x.Elements("book").Select(z => z.Value)
                                )
                        })
                    );

                }

            }
            catch (Exception ex)
            {
                Status = ex.Message;
            }
        }

        public void SaveData()
        {
            try
            {
                XDocument doc = new XDocument(
                    new XElement("scanned",
                        AllNumbers.Select(x =>
                            new XElement("isbn", x.Isbn, x.Copies.Select(z => new XElement("book", z)))
                        )
                        ));
                doc.Save("isbn.txt");
            }
            catch (Exception ex)
            {
                Status = ex.Message;
            }
        }

        public MainWindowViewModel()
        {
            LoadData();
        }

        public Window View()
        {
            BarLog = new ObservableCollection<string>();
            mainWindow = new MainWindow();
            mainWindow.DataContext = this;
            BarcodeReader br = new BarcodeReader();
            br.BarcodeEvent += new EventHandler<BarcodeEventArgs>(br_BarcodeEvent);
            br.BarcodeCharEvent += new EventHandler<BarcodeCharEventArgs>(br_BarcodeCharEvent);
            br.Start(mainWindow);
            return mainWindow;
        }

        void br_BarcodeCharEvent(object sender, BarcodeCharEventArgs e)
        {
            BarLog.Add(e.Char);
        }

        void br_BarcodeEvent(object sender, BarcodeEventArgs e)
        {
            Animate = false;
            //BarLog = new ObservableCollection<string>( BarcodeReader.Log );
            string barcode = e.Data;
            if (e.Data.StartsWith("BOOK"))
                ScannedCopy(barcode);
            else
                ScannedBook(barcode);
            Animate = true;
        }

        private void ScannedBook(string barcode)
        {
            SelectedTitle = AllNumbers.Where(x => x.Isbn == barcode).FirstOrDefault();
            BackgroundColor = Colors.Green;
            if (SelectedTitle == null)
            {
                SelectedTitle = new TitleAndCopies { Isbn = barcode };
                AllNumbers.Add(SelectedTitle);
                SaveData();
            }
        }

        private void ScannedCopy(string barcode)
        {
            var v = AllNumbers.SelectMany(x => x.Copies).Where(x => x == barcode);
            BackgroundColor = Colors.Red;
            if (v.Count() == 0)
                if (SelectedTitle != null)
                {
                    BackgroundColor = Colors.Green;
                    SelectedTitle.Copies.Add(barcode);
                    SaveData();
                }
        }

    }
}
